package com.ruoyi.account.service;

import com.ruoyi.account.domain.Expense;
import com.ruoyi.account.mapper.ExpenseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// src/main/java/com/ruoyi/account/service/
@Service
public class ExpenseService {
    @Autowired
    private ExpenseMapper expenseMapper;

    @Transactional
    public void addExpense(Expense expense) {
        expenseMapper.insertExpense(expense);
    }

    public Map<Long, BigDecimal> calculateDebts(Long ledgerId) {
        Expense expense1 = new Expense();
        expense1.setLedgerId(ledgerId);
        List<Expense> expenses = expenseMapper.selectExpenseList(expense1);
        Map<Long, BigDecimal> netMap = new HashMap<>();

        for (Expense expense : expenses) {
            // 支付人支出增加
            netMap.merge(expense.getPayerId(), expense.getAmount(), BigDecimal::add);

            // 分割 participantIds 并计算每人分摊金额
            String[] participantArray = expense.getParticipantIds().split(",");
            BigDecimal shareAmount = expense.getAmount()
                    .divide(new BigDecimal(participantArray.length), 2, RoundingMode.HALF_UP);

            // 每个承担者支出减少
            for (String pidStr : participantArray) {
                Long pid = Long.parseLong(pidStr);
                netMap.merge(pid, shareAmount.negate(), BigDecimal::add);
            }
        }

        return netMap;
    }

    /**
     * 计算指定账本的总支出
     */
    public BigDecimal getTotalExpense(Long ledgerId) {
        BigDecimal total = expenseMapper.selectTotalExpenseByLedgerId(ledgerId);
        return total != null ? total : BigDecimal.ZERO; // 处理 null 值
    }

    public List<Expense> getListExpense(Expense expense){
        List<Expense> expenseList=expenseMapper.selectExpenseList(expense);
        return expenseList;
    }
}